<script setup lang="ts">
import { computed, nextTick, reactive, watch } from 'vue';
import MD5 from 'crypto-js/md5';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { roleSelectEnum, sexSelectEnum } from '@/enum';
import { userCreateApi, userEditApi } from '@/service/api/businessApi';

defineOptions({
  name: 'UserOperateDrawer'
});

interface Props {
  operateType: AntDesign.TableOperateType;
  rowData?: any | null;
  unitList: any[];
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, resetFields } = useAntdForm();
const { defaultRequiredRule, formRules } = useFormRules();

const title = computed(() => {
  const titles: Record<AntDesign.TableOperateType, string> = {
    add: '新增用户',
    edit: '编辑用户'
  };
  return titles[props.operateType];
});

const model: any = reactive(createDefaultModel());

function createDefaultModel(): any {
  return {
    sex: ''
  };
}

const rules: any = {
  loginCode: formRules.phone,
  password: defaultRequiredRule,
  userType: defaultRequiredRule,
  orgId: defaultRequiredRule
};

/** the enabled role options */
async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    await nextTick();
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

const doAddSubmit = async () => {
  const res = await userCreateApi({
    ...model,
    password: MD5(model.password).toString()
  });
  if (res.error === null) {
    window.$message?.success('新增成功');
    closeDrawer();
    emit('submitted');
  }
};
const doEditSubmit = async () => {
  const res = await userEditApi({
    ...model,
    subscribed: undefined,
    receiveAlarm: undefined
  });
  if (res.error === null) {
    window.$message?.success('更新成功');
    closeDrawer();
    emit('submitted');
  }
};

async function handleSubmit() {
  await validate();
  if (props.operateType === 'add') {
    await doAddSubmit();
  }
  if (props.operateType === 'edit') {
    await doEditSubmit();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    resetFields();
  }
});
</script>

<template>
  <AModal v-model:open="visible" :title="title" :width="560" :maskClosable="false">
    <AForm ref="formRef" layout="vertical" :model="model" :rules="rules">
      <AFormItem label="用户账号" name="loginCode">
        <AInput v-model:value="model.loginCode" placeholder="请输入用户账号" />
      </AFormItem>
      <AFormItem v-if="props.operateType === 'add'" label="用户密码" name="password">
        <AInput v-model:value="model.password" placeholder="请输入用户密码" />
      </AFormItem>
      <AFormItem label="用户昵称" name="userName">
        <AInput v-model:value="model.userName" placeholder="请输入用户昵称" />
      </AFormItem>
      <AFormItem label="用户角色" name="userType">
        <ASelect v-model:value="model.userType" :options="roleSelectEnum" placeholder="请选择用户角色" />
      </AFormItem>
      <AFormItem label="所属单位" name="orgId">
        <ASelect
          v-model:value="model.orgId"
          :options="unitList"
          :field-names="{ label: 'name', value: 'id', options: 'options' }"
          placeholder="请选择所属单位"
        />
      </AFormItem>
      <AFormItem label="用户性别" name="sex">
        <ARadioGroup v-model:value="model.sex">
          <ARadio v-for="item in sexSelectEnum" :key="item.value" :value="item.value">
            {{ item.label }}
          </ARadio>
        </ARadioGroup>
      </AFormItem>
    </AForm>
    <template #footer>
      <ASpace :size="16">
        <AButton @click="closeDrawer">取消</AButton>
        <AButton type="primary" @click="handleSubmit">确认</AButton>
      </ASpace>
    </template>
  </AModal>
</template>

<style scoped></style>
